/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus.extension.net.testutil;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class SimpleFuture {
    private volatile boolean ready = false;
    private volatile Object value;
    private Object waitObject = new Object();;

    public void set(Object value) {
        synchronized(waitObject) {
            this.value = value;
            ready = true;
            waitObject.notifyAll();
        }
    }

    public Object get(int timeout) throws InterruptedException, ExecutionException, TimeoutException {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.submit(new Runnable() {
            public void run() {
                try {
                    get();
                } catch (InterruptedException e) {
                }
            }
        }).get(timeout, TimeUnit.MILLISECONDS);
        return value;
    }

    public Object get() throws InterruptedException {
        synchronized(waitObject) {
            while (!ready) {
                waitObject.wait();
            }
        }
        return value;
    }

    public void reset() {
        synchronized (waitObject) {
            ready = false;
            value = null;
        }
    }
}
